package com.make.house.api.utils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.make.house.api.common.ECConstant;
import com.make.house.api.controller.reponse.upload.FileUploadResponseBean;
import com.make.house.api.controller.reponse.upload.FileUploadResponseDataBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;

/**
 * Created by xujun on 2017/11/20.
 * 又拍云的公共处理类
 */
public class UpyunUtil {
    static Logger logger = LoggerFactory.getLogger(UpyunUtil.class);

    //又拍云的回调地址，又拍云服务器请求，并且传入是否成功和成功信息
    public static final String UpyunCallback = "http://www.siwuk.cn" + ECConstant.API_REQUEST_BASE_URL + "/file/upload/callback";

    public UpyunUtil() {
    }

    public static FileUploadResponseBean createResult(String uid, int imageReq, int fileReq, String appKey, String callbackUrl) throws SQLException, JSONException {
        FileUploadResponseBean dto = new FileUploadResponseBean();
        if(imageReq > 0) {
            dto.setImage(makePolicy(uid, BucketEnum.IMAGE, appKey, callbackUrl));
        }
        if(fileReq > 0) {
            dto.setFile(makePolicy(uid, BucketEnum.FILE, appKey, callbackUrl));
        }
        return dto;
    }

    private static FileUploadResponseDataBean makePolicy(String uid, BucketEnum bucketEnum, String appKey, String callbackUrl) {
        try {
            JSONObject e = new JSONObject();
            long expire_at = System.currentTimeMillis() / 1000L + 1800L;
            e.put("bucket", bucketEnum.getProfile());
            e.put("expiration", expire_at);
            e.put("save-key", makeSaveKey(uid, bucketEnum));
            e.put("content-length-range", "1,20479999");

            StringBuilder returnURLBuffer = new StringBuilder();
            returnURLBuffer.append(callbackUrl);
            returnURLBuffer.append("?uid=").append(uid);
            returnURLBuffer.append("&type=").append(bucketEnum);
            returnURLBuffer.append("&host=").append(bucketEnum.getUrl());
            returnURLBuffer.append("&APP_KEY=").append(appKey);
            returnURLBuffer.append("&cross=1");
            e.put("return-url", returnURLBuffer.toString());
            String policy = DataUtil.getBASE64(e.toString());

            String signature = DataUtil.getMD5Str(policy + "&" + bucketEnum.getKey());

            return FileUploadResponseDataBean.newBuilder()
                    .withPolicy(policy)
                    .withSignature(signature)
                    .withPath(bucketEnum.getProfile())
                    .withExpireAt(expire_at).build();
        } catch (JSONException e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    private static String makeSaveKey(String uid, BucketEnum bucketEnum) {
        String userFolder = MD5Util.getMD5(uid);
        return String.format(bucketEnum.getSaveFormat(), userFolder);
    }

    /**
     * 现在用的又拍云的测试地址，engineer-file.test.upcdn.net
     * 等备案成功缓存我们自己的
     */
    public enum BucketEnum {
        IMAGE("engineer-calculate", "www.image.siwuk.cn", "wE3++0drwOjUNbVi9T+idib+FB4=", "/%s/{filemd5}/{filename}.{suffix}"),
        FILE("engineer-file", "www.upyun.siwuk.cn", "sgc+41+fq8xu1oJIlO6ook5wb6k=", "/%s/{filemd5}.{suffix}");

        private String profile;
        private String url;
        private String key;
        private String saveFormat;

        BucketEnum(String profile, String url, String key, String saveFormat) {
            this.profile = profile;
            this.url = url;
            this.key = key;
            this.saveFormat = saveFormat;
        }

        public String getProfile() {
            return profile;
        }

        public String getUrl() {
            return url;
        }

        public String getKey() {
            return key;
        }

        public String getSaveFormat() {
            return saveFormat;
        }
    }

}
